/*
    This file is part of the KDE libraries
    SPDX-FileCopyrightText: 2020 David Faure <faure@kde.org>

    SPDX-License-Identifier: LGPL-2.0-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
*/

#include "widgetsdeleteortrashjobhandler.h"
#include "deleteortrashjob.h"
#include "openurljob.h"

#include <KConfigGroup>
#include <KJobWidgets>
#include <KLocalizedString>

#include <QApplication>
#include <QWidget>

KIO::WidgetsDeleteOrTrashJobHandler::WidgetsDeleteOrTrashJobHandler(QObject *parent)
    : KIO::DeleteOrTrashJobHandlerInterface(parent)
{
}

KIO::WidgetsDeleteOrTrashJobHandler::~WidgetsDeleteOrTrashJobHandler() = default;

void KIO::WidgetsDeleteOrTrashJobHandler::setWindow(QWidget *widget)
{
    m_parentWidget = widget;
}

void KIO::WidgetsDeleteOrTrashJobHandler::askUserDeleteOrTrash(KJob *job,
                                                               const QList<QUrl> &urls,
                                                               AskUserActionInterface::DeletionType deletionType,
                                                               AskUserActionInterface::ConfirmationType confirm)
{
    QWidget *parentWidget = nullptr;

    if (job) {
        parentWidget = KJobWidgets::window(job);
    }

    if (!parentWidget) {
        parentWidget = m_parentWidget;
    }

    if (!parentWidget) {
        parentWidget = qApp->activeWindow();
    }

    auto *deleteOrTrashJob = new KIO::DeleteOrTrashJob(urls, deletionType, confirm, parentWidget);
    connect(deleteOrTrashJob, &KJob::result, this, [deleteOrTrashJob, this]() {
        const int errCode = deleteOrTrashJob->error();

        qWarning() << "broken-symlinks: widgetsdeleteortrashjobhandler.cpp -> errCode" << errCode;

        if (errCode == 0) {
            Q_EMIT result(true);
        } else if (errCode == KIO::ERR_USER_CANCELED) {
            Q_EMIT canceled();
        } else {
            Q_EMIT result(false);
        }
    });
    deleteOrTrashJob->start();
}

#include "moc_widgetsdeleteortrashjobhandler.cpp"
